import 'package:extended_text/extended_text.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:xreader/logs/log.dart';

class MyInfoPage extends StatelessWidget {
  const MyInfoPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    print("MyInfoPage====>build===》");
    return Center(
      child: CustomTextToolbar(),
    );
  }
}

class CustomTextToolbar extends StatefulWidget {
  @override
  _CustomTextToolbarState createState() => _CustomTextToolbarState();
}

class _CustomTextToolbarState extends State<CustomTextToolbar> {
  List<String> customOptions = [
    'Option 1',
    'Option 2',
    'Option 3',
  ];

  //ExtendedTextSelectionPointerHandler

  String selectedOption = '';
  String text = "我是一名中国共产党员，嗡嗡嗡倒计时开始的 第四季亏损";
  @override
  Widget build(BuildContext context) {
    return SelectableText.rich(
      TextSpan(
        //text: 'This is a selectable text with custom toolbar options.',
        text: text,
        style: TextStyle(fontSize: 20),
        children: <InlineSpan>[
          TextSpan(
            text:"第三阶段是多少低价快速的是"
          )
        ]
      ),
      // toolbarOptions: ToolbarOptions(
      //   copy: true,
      //   selectAll: true,
      //   cut: true,
      // ),
      contextMenuBuilder: _textFieldContextMenuBuilder,
      onTap: () {
        //showCustomToolbar(context);
      },
      onSelectionChanged: (TextSelection sel, SelectionChangedCause? cause){

        print("start=${sel.start} end=${sel.end} ");

      },
    );
  }

  static Widget _textFieldContextMenuBuilder(BuildContext context, EditableTextState editableTextState) {
    return CustomTextSelectionToolbar.editableText(
      editableTextState: editableTextState,
    );
  }

  void showCustomToolbar(BuildContext context) {
    final RenderBox renderBox = context.findRenderObject() as RenderBox;
    final Offset offset = renderBox.localToGlobal(Offset.zero);

    showMenu(
      context: context,
      position: RelativeRect.fromLTRB(
        offset.dx,
        offset.dy + renderBox.size.height,
        offset.dx + renderBox.size.width,
        offset.dy + renderBox.size.height + 50,
      ),
      items: customOptions.map((String option) {
        return PopupMenuItem<String>(
          value: option,
          child: Text(option),
        );
      }).toList(),
    ).then((value) {
      if (value != null) {
        setState(() {
          selectedOption = value;
        });
      }
    });
  }
}


class CustomTextSelectionToolbar extends AdaptiveTextSelectionToolbar {
  const CustomTextSelectionToolbar(
      {super.key, required super.children, required super.anchors});

  CustomTextSelectionToolbar.editableText({
    super.key,
    required EditableTextState editableTextState,
  }) : super.editableText(editableTextState: editableTextState);

  @override
  Widget build(BuildContext context) {
    // If there aren't any buttons to build, build an empty toolbar.
    if ((children != null && children!.isEmpty) ||
        (buttonItems != null && buttonItems!.isEmpty)) {
      return const SizedBox.shrink();
    }
    List<Widget> resultChildren = <Widget>[];
    resultChildren.add(SelectionToolBarButton(
        width: 100,
        height: 50,
        icon:Icon(
          Icons.copy,
          color: Colors.white,
          size: 14,
        ), title: '复制', onPressed: () async {
          print("复制======》");
          if(buttonItems != null && buttonItems!.length > 0 ){
            final ContextMenuButtonItem item = buttonItems![0];
            item.onPressed!();
            ClipboardData? data = await Clipboard.getData(Clipboard.kTextPlain);
            if(data != null){
              print("复制出的文本===》${data.text}");
            }
          }
    },));

    resultChildren.add(SelectionToolBarButton(
      width: 100,
      height: 50,
      icon:Icon(
        Icons.search,
        color: Colors.white,
        size: 14,
      ), title: '查询', onPressed: () async {
      print("查询======》");
      if(buttonItems != null && buttonItems!.length > 0 ){
        final ContextMenuButtonItem item = buttonItems![0];
        item.onPressed!();
        ClipboardData? data = await Clipboard.getData(Clipboard.kTextPlain);
        if(data != null){
          print("查询按钮---复制出的文本===》${data.text}");
        }
      }
    },));
    resultChildren.add(SelectionToolBarButton(
      width: 100,
      height: 50,
      icon:Icon(
        Icons.add,
        color: Colors.white,
        size: 14,
      ), title: '记笔记', onPressed: () async {
      print("查询======》");
      if(buttonItems != null && buttonItems!.length > 0 ){
        final ContextMenuButtonItem item = buttonItems![0];
        item.onPressed!();
        ClipboardData? data = await Clipboard.getData(Clipboard.kTextPlain);
        if(data != null){
          print("查询按钮---复制出的文本===》${data.text}");
        }
      }
    },));
    // for (int i = 0; i < buttonItems!.length; i++) {
    //   final ContextMenuButtonItem buttonItem = buttonItems![i];
    //   print("${buttonItem.label}--${buttonItem.type}");
    //   resultChildren.add(SelectionToolBarButton(
    //     width: 100,
    //     height: 50,
    //     icon: (i == 0)?Icon(
    //       Icons.cut,
    //       color: Colors.white,
    //       size: 14,
    //     ):Icon(
    //       Icons.copy,
    //       color: Colors.white,
    //       size: 16,
    //     ),
    //     title: getButtonLabelString(context, buttonItem),
    //     onPressed:(){
    //       if(buttonItem.onPressed != null){
    //         buttonItem.onPressed!();
    //       }
    //     }
    //   ));
    // }

    switch (Theme.of(context).platform) {
      case TargetPlatform.iOS:
        return CupertinoTextSelectionToolbar(
          anchorAbove: anchors.primaryAnchor,
          anchorBelow: anchors.secondaryAnchor == null
              ? anchors.primaryAnchor
              : anchors.secondaryAnchor!,
          children: resultChildren,
        );
      case TargetPlatform.android:
        return TextSelectionToolbar(
          anchorAbove: anchors.primaryAnchor,
          anchorBelow: anchors.secondaryAnchor == null
              ? anchors.primaryAnchor
              : anchors.secondaryAnchor!,
          children: resultChildren,
        );
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.windows:
        return DesktopTextSelectionToolbar(
          anchor: anchors.primaryAnchor,
          children: resultChildren,
        );
      case TargetPlatform.macOS:
        return CupertinoDesktopTextSelectionToolbar(
          anchor: anchors.primaryAnchor,
          children: resultChildren,
        );
    }
  }

  /// Returns the default button label String for the button of the given
  /// [ContextMenuButtonType] on any platform.
  static String getButtonLabelString(BuildContext context, ContextMenuButtonItem buttonItem) {
    if (buttonItem.label != null) {
      return buttonItem.label!;
    }

    switch (Theme.of(context).platform) {
      case TargetPlatform.iOS:
      case TargetPlatform.macOS:
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.windows:
        assert(debugCheckHasMaterialLocalizations(context));
        switch (buttonItem.type) {
          case ContextMenuButtonType.cut:
            return "剪切";
          case ContextMenuButtonType.copy:
            return "复制";
          case ContextMenuButtonType.paste:
            return "粘贴";
          case ContextMenuButtonType.selectAll:
            return "选择全部";
          case ContextMenuButtonType.custom:
            return '';
          default:
            return "-";
        }
    }
  }
}



//自定义工具栏按钮
class SelectionToolBarButton extends StatelessWidget {
  const SelectionToolBarButton({
    super.key,
    required this.width,
    required this.height,
    required this.icon,
    required this.title,
    required this.onPressed,
  });

  final double width;
  final double height;
  final Icon icon;
  final String title;
  final VoidCallback onPressed;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        onPressed();
      },
      child: Container(
        color: Colors.black87,
        width: width,
        height: height,
        alignment: Alignment.center,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            icon,
            SizedBox(
              width: 5,
            ),
            Text(
              title,
              style: TextStyle(
                fontSize: 15,
                color: Colors.white,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

